/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: zhangti
 * @Date: 2020-01-14 10:30:23
 * @LastEditors  : sueRimn
 * @LastEditTime : 2020-01-16 12:55:58
 */
/**
 * 测控分析
 * 分析导弹经过雷达监控范围
 * 计算开始时间和结束时间
 */

import Analyser from './analyser.js';
import config from './config.js';
import Orbit from '../../libs/Orbit.js';
export default class OrbitAnalyze extends Analyser{
    /**
	 * 初始化
	 * @param {*} supers 
	 * @param {*} opt
	 */
	constructor(supers,opt){
		super(supers);
		//opt = Cesium.defaultValue(opt, Cesium.defaultValue.EMPTY_OBJECT);	//判断是否有值
		this.opt = opt;
		this.analyser();
	}
	/**
	 * 创建分析
	 */
	analyser(){
        if (!Cesium.defined(this._viewer)) {
            throw new Cesium.DeveloperError('viewer is required.');
        }
        if(!this.opt){
            return false;
        }
		this.orbitPrototype = new OrbitPrototype(this);
	}
    
}
/**
 * 过境分析类
 */
class OrbitPrototype{
    constructor(_that){
		this._that = _that;
		this.options = _that.opt;
		this.viewer = _that._viewer;
        this.entitys = _that.entitys;
        this.tools = _that.Tools;
        this.mouseManager = _that.mouseManager;

        this._passEntity = [];
        this._radars = [];
        this._interPoints = [];
        this._groundPonit = [];
        this._sateLine = [];
        this.czmlDataSource = null;
        this.analyzeResult = null;
        this.entityCzml = [];
        //地面测试点
        this.groundPoint = [
            {name:"测试站No.1",lat: 42.414136487719354, lon: 100.52056873233481, alt: 0,scope:3600},
            {name:"测试站No.2",lat: 42.42522146204617, lon: 109.85947530942975, alt: 0,scope:3000},
            {name:"测试站No.3",lat: 33.1819896042328, lon: 109.5591230090901, alt: 0,scope:4000},
            {name:"测试站No.4",lat: 32.019262705194734, lon: 101.73699414432289, alt: 0,scope:3800},
            {name:"测试站No.5",lat: 27.496123837273654, lon: 103.82420725508969, alt: 0,scope:3000},
            {name:"测试站No.6",lat: 26.949808853110465, lon: 114.53228575748204, alt: 0,scope:1800},
            {name:"测试站No.7",lat: 35.685974970635534, lon: 93.2030228474047, alt: 0,scope:3200},
            {name:"测试站No.8",lat: 24.73499910338626, lon: 106.24244324184826, alt: 0,scope:1000},
            {name:"测试站No.9",lat: 41.73492679655367, lon: 121.17656582042726, alt: 0,scope:3500}
        ]
		this.load();
    }
    //加载数据
    load(){
        if(!this.options.data){
            return false;
        }
        //添加地面站点和雷达
       this.parseGroundPoint().then(res =>{
            //解析czml
            this.parseCzml(this.options.data).then(res =>{
                //解析轨道数据
                this.parseOrbit().then(computePass => {    
                    //计算结果
                    this.compute(computePass).then(res =>{
                        //添加轨道
                        this.viewer.dataSources.add(this.czmlDataSource);
                    });
                });
            })
       });;
    }
     /**
     *  加载轨道计算
     * @param {*} file 
     */
    loadOrbitCompute(call) {
        let orbits = [];
        if (this.options.file) {
            let fileDataUrl = URL.createObjectURL(file);
            fetch(fileDataUrl, {
                mode: "no-cors",
            }).then(response => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                return response;
            }).then(response => response.text()).then(data => {
                const lines = data.split(/\r?\n/);
                for (let i = 3; i < lines.length; i + 3) {
                    let tle = lines.splice(i - 3, i).join("\n");
                    let name = tle.split("\n")[0].trim();
                    if (tle.startsWith("0 ")) {
                        name = name.substring(2);
                    }
                    orbits.push(new Orbit(name, tle));
                }
                call(orbits);
            }).catch(function (error) {
                console.log(error);
            });
        }else{
            if(this.options.tle){
                orbits.push(new Orbit(this.options.tleName, this.options.tle));
                call(orbits);
            }
        }
    }
    //解析轨道数据
    parseOrbit(file){
        return new Promise((resolve,reject) =>{
            this.loadOrbitCompute((orbits)=>{
                if (orbits.length == 0) return false;
                let computePass = [];
                for (let i in this._groundPonit) {
                    let radar = this._groundPonit[i];
                    for (let o in orbits) { //每个雷达对于的轨道
                        let orbit = orbits[o];
                        if (!radar.longitude) continue;
                        let passeds = orbit.computeOrbitPasses({ longitude: radar.longitude, latitude: radar.latitude, height: 0, zyjl: radar.zyjl }, this.options.stime, this.options.etime);
                        //     let passeds = orbit.computePasses({longitude:radar.longitude,latitude:radar.latitude,height:0,zyjl:radar.zyjl},$this.stime,$this.etime);
                        if (passeds.length > 0) { //存在过境的雷达
                            computePass.push({ radar: radar, pass: passeds });
                        }
                    }
                }
                resolve(computePass);//计算完成解析数据
            });
            
        });
    }
    /**
     * 计算
     * @param {*} czml 
     */
    compute(computePass){
        return new Promise((resolve,reject) =>{
            let radarEntity = [],nodes =[];
                for (let i in computePass) {
                    let result = computePass[i];
                    let radar = result.radar, pass = result.pass;
                    if (pass.length > 0) { //有经过的
                        for (let p in pass) {
                            //创建点
                            let { bool, newStartLonLat, newStopLonLat } = this.matchCzml(pass[p], radar);
                            if (bool) { //判断当前时间点是否在测控距离内
                                nodes.push({
                                    time: new Date(pass[p].start).toLocaleString() + ' - ' + new Date(pass[p].end).toLocaleString(),
                                    start_point: newStartLonLat,
                                    stop_point: newStopLonLat,
                                    azimuthApex: pass[p].azimuthApex,
                                    duration: pass[p].duration,
                                    r_lon: radar.longitude,
                                    r_lat: radar.latitude,
                                    pid:radar.id,
                                    startTime:pass[p].start,
                                    endTime:pass[p].end,
                                    name:radar.name
                                })
                                radarEntity.push({ radar: radar });
                            }
                        }
                    }
                }
                this.createData(radarEntity); //重新创建
                resolve(this.createNodeTree(nodes));
        });
    }
    //和czml匹配
    matchCzml(pass, radar) {
        let bool = false, newStartLonLat, newStopLonLat;
        for (let i in this.entityCzml) {
            let entity = this.entityCzml[i]; //czml
            let start_position = entity.position.getValue(Cesium.JulianDate.fromDate(new Date(pass.start)));
            let end_position = entity.position.getValue(Cesium.JulianDate.fromDate(new Date(pass.end)));
           
            //匹配成功
            if (start_position) {
                let startDistance = this.tools._distance(start_position, radar.position.getValue());
               // console.log(startDistance);
                if ((startDistance / 1000) < parseInt(radar.scope)) {
                    bool = true;
                    newStartLonLat = this.mouseManager.worldToLonlat(start_position);
                    newStopLonLat = this.mouseManager.worldToLonlat(end_position);
                    let pentity = this.entitys.createPoint(start_position, '设备:' + radar.name + '\n 开始: ' + new Date(pass.start).toLocaleString() + '\n 间隔: ' + pass.duration + '(ms) \n 高度: ' + newStartLonLat.alt + '\n 经度：' + newStartLonLat.lon + "\n 纬度：" + newStartLonLat.lat, true);
                    pentity.passid = pass.oid;
                    pentity.label.show = false;
                    pentity.rid = radar.id;
                    pentity.dateTime = pass.start;
                    pentity.status = 'start';
                    //pentity.label.show = false;
                    this._passEntity.push(pentity);
                }
            }
            if (end_position) {
                let endDistance = this.tools._distance(end_position, radar.position.getValue());
                if ((endDistance / 1000) < parseInt(radar.scope)) {
                    bool = true;
                    newStartLonLat = this.mouseManager.worldToLonlat(start_position);
                    newStopLonLat = this.mouseManager.worldToLonlat(end_position);
                    let pentity = this.entitys.createPoint(end_position, '设备:' + radar.name + '\n 结束: ' + new Date(pass.end).toLocaleString() + '\n 高度: ' + newStopLonLat.alt + '\n 经度：' + newStopLonLat.lon + "\n 纬度：" + newStopLonLat.lat, true);
                    pentity.passid = pass.oid;
                    pentity.label.show = false;
                    pentity.rid = radar.id;
                    pentity.dateTime = pass.end;
                    pentity.status = 'end';
                    //pentity.label.show = false;
                    this._passEntity.push(pentity);
                }
            }
        };
        return { bool, newStartLonLat, newStopLonLat };
    }
    //解析czml
    parseCzml(data){
        return new Promise((resolve,reject) =>{
            let newCzml = data.czml.replace(/[\n\r]/g, '');
            Cesium.CzmlDataSource.load(JSON.parse(newCzml)).then((dataSource) => {
                this.czmlDataSource = dataSource;
                //存储卫星轨迹
                for (let i in dataSource.entities._entities._array) {
                    let sateEntity = dataSource.entities._entities._array[i];
                    this.entityCzml.push(sateEntity);
                }
                resolve();
            });
        });
        
    }
    /**
     * 解析站点和雷达
     */
    parseGroundPoint(){
        let $this = this;
        //创建雷达
        function createRadar(dentity){
            let rentity = $this.entitys.createEntity();
            rentity.name = dentity.name;
            rentity.position = dentity.position;
            rentity.ellipsoid = $this.entitys.getEllipsoid({
                r: dentity.scope * 1000
            });
            rentity.ide = "ellipsoid";
            rentity.pid = dentity.id;
            $this._radars.push($this.entitys.add(rentity));
        }
        //创建地面点
        function createGroundPoint(items){
            let dentity = $this.entitys.createEntity();
            dentity.name = items.name;
            dentity.longitude = items.lon;
            dentity.latitude = items.lat;
            dentity.position = Cesium.Cartesian3.fromDegrees(items.lon, items.lat, items.alt)
            dentity.label = $this.entitys.getLabel(items.name);
            dentity.billboard = $this.entitys.getBillboard(config.STATICDIR +'/Cesium/Apps/SampleData/kml/facilities/GroundStation.png');
            dentity.scope = items.scope;

            let dentityObj = $this.entitys.add(dentity);
            $this._groundPonit.push(dentityObj);
            
            return dentityObj;
        }
        return new Promise((resolve, reject)=>{
            
            if(this.groundPoint.length == 0)return false;
            for(let i in this.groundPoint){
                let items = this.groundPoint[i];
                createRadar(createGroundPoint(items));
            }
            resolve();
        })
    }
    //创建
    createData(computePass){
        console.log('-- 计算完成,重新绘制 --');
        //清除所有雷达
        for (let i in this._radars) {
            this.entitys.remove(this._radars[i]);
        }
        for (let i in this._groundPonit) {
             this.entitys.remove(this._groundPonit[i]);
        }
       
        if (computePass.length > 0) {
             //对雷达去重
             let newPassPoint = this.tools._uniqueArrTwo(computePass,'radar','id');
              //添加地面设备
             for(let i in newPassPoint){
                this._passEntity.push(this.entitys.add(newPassPoint[i].radar));
            }
           
            //添加雷达范围
            for(let i in newPassPoint){
                for (let j in this._radars) {
                    if(newPassPoint[i].radar.id == this._radars[j].pid){
                        this._radars[j].show = false;
                        this._passEntity.push(this.entitys.add(this._radars[j]));
                        break;
                    }
                }
            }
          
        }
        this._radars = []; //清除所有设备 重新绘制
        this._groundPonit = [];
    }
    /**
     * 创建节点控制
     */
    createNodeTree(nodes){
       console.log(nodes);
       let nodeData = [],tree = layui.tree,$this = this;
       //提取父节点
       let pNode = this.tools._uniqueArrOne(nodes,'pid');
       for(let i in pNode){
            let childrens = [];
            for(let j in nodes){
                if(pNode[i].pid == nodes[j].pid){
                    childrens.push({title:nodes[j].time,
                        id:this.tools._guid(),
                        oid:nodes[j].pid,
                        startTime:nodes[j].startTime,
                        endTime:nodes[j].endTime
                    });
                }
            }
            nodeData.push({title:pNode[i].name,id:this.tools._guid(),spread:true,children:childrens,oid:pNode[i].pid});
       }
       //筛选节点
       function switchBox(node,checked){
           if(!node.children){ //子节点
                if($this._passEntity.length > 0){
                    $this.viewer.clock.shouldAnimate = false;
                    for(let i in $this._passEntity){
                        //开始
                        if(node.oid == $this._passEntity[i].rid & node.startTime == $this._passEntity[i].dateTime){
                            $this.viewer.clock.currentTime = Cesium.JulianDate.fromDate(new Date(node.startTime));
                            $this.viewer.clock.shouldAnimate = true;
                            let position = $this.mouseManager.worldToLonlat($this._passEntity[i].position.getValue()); //转换经纬度 不然有偏差
                            $this.viewer.camera.setView({ destination: Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.alt * 2)});
                            if (checked) {
                                $this._passEntity[i].label.show = checked;
                            } else {
                                $this._passEntity[i].label.show = checked;
                            }
                            setTimeout(() => {
                                $this.viewer.clock.shouldAnimate = false;
                            }, 0);
                            break;
                        }
                        //结束
                        if(node.oid == $this._passEntity[i].rid & node.endTime == $this._passEntity[i].dateTime){
                            $this.viewer.clock.currentTime = Cesium.JulianDate.fromDate(new Date(node.endTime));
                            $this.viewer.clock.shouldAnimate = true;
                            let position = $this.mouseManager.worldToLonlat($this._passEntity[i].position.getValue()); //转换经纬度 不然有偏差
                            $this.viewer.camera.setView({ destination: Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.alt * 2)});
                            $this._passEntity[i].label.show = checked;
                            setTimeout(() => {
                                $this.viewer.clock.shouldAnimate = false;
                            }, 0);
                            break;
                        }
                    }
                }
           }else{ //父节点
                 for(let i in $this._passEntity){
                     if(node.oid == $this._passEntity[i].pid){
                        $this._passEntity[i].show = checked;
                     }
                 }
           }
       }
       //创建树
       function createPassOpen(){
            tree.render({
                elem: '#passOpen'
                , data: nodeData
                , showCheckbox: true  //是否显示复选框
                //, edit: ['add', 'update', 'del'] //操作节点的图标
                , id: 'layerDivId'
                , isJump: true //是否允许点击节点时弹出新窗口跳转
                , oncheck: function (obj) {
                    switchBox(obj.data,obj.checked)
                }
                , click: function (obj) {
                    layer.msg(JSON.stringify(obj.data));
                }
            });
       }
       this.tools.openCommonDiv({ 
           'id':'layerDivOpen',
           'title': '过境分析', 
           'area': ['20%', '60%'], 
           'offset': ['10%', '5%'], 
           'content': `<div id="passOpen"></div>`, 
           'fn': createPassOpen }    
        );
       
    }
}